//
//  AppDelegate.m
//  FaceRecognition
//
//  Created by Sylar on 2016/11/28.
//  Copyright © 2016年 Sylar. All rights reserved.
//
/*
 {
 aps =     {
 alert = "\U4e0d\U662f,\U6765\U81ea\U4e0d,\U7533\U8bf7\U8bbf\U95ee\U5b66\U6821\Uff0c\U8bf7\U5ba1\U6279";
 badge = 0;
 "content-available" = 1;
 sound = "";
 };
 classid = 0;
 eventid = "";
 infoid = 49;
 moveto = 4005;
 msgid = 2580;
 url = "";
 }
 */

#import "AppDelegate.h"
#import "LoginViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <Bugly/Bugly.h>
#import "BPush.h"
#import <UserNotifications/UserNotifications.h>
#import "SY_Activity.h"
#import "SY_Activity_Model.h"
#import "SYMessageTool.h"
#import "FR_MessageListViewController.h"

static BOOL isBackGroundActivateApplication;
@interface AppDelegate () <UIAlertViewDelegate>

@property (nonatomic, copy) NSString *chinnelid;

@end

@implementation AppDelegate


@synthesize myClasses;
@synthesize parentTypes;
@synthesize classgraders;
@synthesize courseList;
@synthesize studentId;
@synthesize isChangeRole;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    isChangeRole=@"yes";
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    //登录状态的通知监听 在登录状态改变的时候触发
    [[NSNotificationCenter defaultCenter] addObserver:self
                                              selector:@selector(loginStateChange:)
                                                  name:KNOTIFICATION_LOGINCHANGE
                                                object:nil];
    
    
    //设置导航栏
    [[UINavigationBar appearance] setBarTintColor:DEFAULTCOLOR];
    
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:18.0], NSFontAttributeName, nil]];
  
//#if DEBUG
//    //开发模式下不收集
//#else
    [self setupBugly];//初始化腾讯bugly
//#endif
   
    //状态栏的设置
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self.window makeKeyAndVisible];
    
    //[self loadOpenPic];
    
    //设置推送字典
    self.notiDict = launchOptions;
    
    [self loginStateChange:nil];
    
    [self checkupVersion];
    
    //注册推送
    [self registerNotification:application launchOptions:launchOptions];
    
    
    
    return YES;
}

/**注册推送*/
- (void)registerNotification:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions {
    
    // iOS10 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  // Enable or disable features based on authorization.
                                  if (granted) {
                                      
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          
                                          [application registerForRemoteNotifications];
                                      });
                                      
                                  }
                              }];
#endif
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    
#if DEBUG
    [BPush registerChannel:launchOptions apiKey:@"1oXwuRk3tX1WlKL0xa8D9Z1q" pushMode:BPushModeDevelopment withFirstAction:@"打开" withSecondAction:@"关闭" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];
#else
    [BPush registerChannel:launchOptions apiKey:@"1oXwuRk3tX1WlKL0xa8D9Z1q" pushMode:BPushModeProduction withFirstAction:@"打开" withSecondAction:@"关闭" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];
#endif
   
    [BPush disableLbs];
   
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [BPush handleNotification:userInfo];
    }
    
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    
    [application registerForRemoteNotifications];
    
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        
        // 网络错误
        if (error) {
            return ;
        }
        if (result) {
            // 确认绑定成功
            if ([result[@"error_code"]intValue]!=0) {
                return;
            }
            // 获取channel_id
            NSString *myChannel_id = [BPush getChannelId];
            _chinnelid = myChannel_id;
            NSLog(@"== myChannel_id %@",myChannel_id);
           
           
           
            if (USERID) { //绑定
                
                [self bindChinnelId];
               
                [self bindChinnelId2];
                
            }
        }
    }];
    
}

//绑定chinelid
- (void)bindChinnelId {
   
   NSLog(@"bindChinnelId = %@",_chinnelid);
   
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:USERID forKey:@"userid"];
    [param setObject:@"0" forKey:@"clienttype"];
     if(_chinnelid!=nil)
     {
        [param setObject:_chinnelid forKey:@"channelid"];
        
     }else
     {
        return;
     }
   
    [param setObject:[SYAccountTool ShareAccount].account.lasttype == 1?SCHOOLID:@"0" forKey:@"scid"];
    

    [Utils Java_get:@"api/setChannelId" parameters:param success:^(NSInteger recode, id jsonObject) {
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)bindChinnelId2{
   
   NSMutableDictionary *param = [NSMutableDictionary dictionary];
   
   [param setObject:USERID forKey:@"userid"];
   [param setObject:@"0" forKey:@"clienttype"];
   if(_chinnelid!=nil)
   {
      [param setObject:_chinnelid forKey:@"channelid"];
      
   }else
   {
      return;
   }
   
   [param setObject:@"api_user_push" forKey:@"method"];
   
   [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
      
   } failure:^(NSInteger recode, NSError *error) {
      
   }];
}
// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}


/**初始化Bugly*/
- (void)setupBugly {
    
    [Bugly startWithAppId:@"0196bb3ad7"];
    
    BuglyConfig *config = [BuglyConfig defaultConfig];
    
#if DEBUG
    config.debugMode = YES;
#endif
    config.reportLogLevel = BuglyLogLevelWarn;
    config.blockMonitorEnable = YES;
    config.blockMonitorTimeout = 1.5;
    config.channel = @"Bugly";
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [self checkupVersion];
}

// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
   
   //    App 收到推送的通知
//   [BPush handleNotification:userInfo];
   
   NSLog(@"通知栏进入");
   
   if (!USERID) {
      
      return;
   }
   
   if (!userInfo) {
      
      return;
   }
   
   
   
   NSLog(@"userInfo = %@",userInfo);
   
   NSDictionary *apsDic = [userInfo objectForKey:@"aps"];
   
   NSString *descriptionStr = [NSString stringWithFormat:@"%@",[apsDic objectForKey:@"alert"]];
   NSString * colorStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"color"]];
   NSString * urlStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"url"]];
   NSString * msgtitleStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"msgtitle"]];
   NSString * nameStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"name"]];
   NSString * logoStr = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"logo"]];
   NSInteger  type = [[userInfo objectForKey:@"type"]integerValue];
   NSInteger moveto = [[userInfo objectForKey:@"moveto"]integerValue];
   NSString * infoidStr = [userInfo objectForKey:@"infoid"];
   NSString * classidStr = [userInfo objectForKey:@"classid"];
   NSString * scidStr = [userInfo objectForKey:@"scid"];
   
   
   
   
   SY_Activity_Model *model = [[SY_Activity_Model alloc] init];
   
   model.description2 = descriptionStr;
   model.color = colorStr;
   model.url = urlStr;
   model.msgtitle = msgtitleStr;
   model.name = nameStr;
   model.logo = logoStr;
   model.type = type;
   model.moveto = moveto;
   model.infoid = infoidStr;
   model.jointime = [self getCurrentTimes];
   model.readState = 0;
   model.apptype = 2;
   model.scid = scidStr;
   model.classid = classidStr;
   
   [SYMessageTool instertBPustMessage:model];
   
   
   
   if (application.applicationState == UIApplicationStateInactive){
      
      NSLog(@"带激活中");
      model.readState = 1;
      [SYMessageTool instertBPustMessage:model];
      
      [SY_Activity shareActivity].instructionArr = @[model];
      [[SY_Activity shareActivity] action];
   
   }else if (application.applicationState == UIApplicationStateActive) {
      
      NSLog(@"使用中");
      
   }else if (application.applicationState == UIApplicationStateBackground) {
      
      NSLog(@"后台");
      
   }
   
   [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMessageList" object:nil];
   
   
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark 支付宝
//=======支付宝
// 友盟相关
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
   //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
   if ([url.host isEqualToString:@"safepay"]) {
      [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
         //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
         
         NSString *a=[resultDic  objectForKey:@"result"];
         NSLog(@"============%@",resultDic);
         
         UIViewController *vc = [Utils getCurrentVC];
         if ([vc.title isEqualToString:@"选择交费方式"]) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PaymentBySchool" object:nil userInfo:resultDic];
         }else if ([vc.title isEqualToString:@"交费失败"]){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RePaymentBySchool" object:nil userInfo:resultDic];
         }else{
            
            NSArray *b = [a componentsSeparatedByString:@"&"];
            for (int i=0; i<b.count; i++) {
               NSString *str=[b objectAtIndex:i ];
               if ([str isEqualToString:@"success=\"true\""] && [[resultDic  objectForKey:@"resultStatus"]isEqualToString:@"9000"]) {
                  
                  
                  
                  UIAlertView *ale=[[UIAlertView alloc]initWithTitle:@"支付成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                  ale.tag = 1002;
                  [ale show];
                  //支付成功后
                  //添加订单信息
                  
               }
            }
         }
         
         
         
         
         
      }];
      
      return YES;
   }
   if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
      
      [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
         //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
         
         NSString *a=[resultDic  objectForKey:@"result"];
         NSArray *b = [a componentsSeparatedByString:@"&"];
         for (int i=0; i<b.count; i++) {
            NSString *str=[b objectAtIndex:i ];
            if ([str isEqualToString:@"success=\"true\""]&&[[resultDic  objectForKey:@"resultStatus"]isEqualToString:@"9000"]) {
               UIAlertView *ale=[[UIAlertView alloc]initWithTitle:@"支付成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
               ale.tag = 1002;
               [ale show];
               //支付成功后
            }
         }
      }];
      return YES;
   }
   
   BOOL result = [UMSocialSnsService handleOpenURL:url];
   
   if (result == FALSE) {
      //调用其他SDK，例如支付宝SDK等
   }
   return result;
}

//// NOTE: 9.0以后使用新API接口
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//   if ([url.host isEqualToString:@"safepay"]) {
//      // 支付跳转支付宝钱包进行支付，处理支付结果
//      [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//         NSLog(@"result = %@",resultDic);
//      }];
//      
//      // 授权跳转支付宝钱包进行支付，处理支付结果
//      [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
//         NSLog(@"result = %@",resultDic);
//         // 解析 auth code
//         NSString *result = resultDic[@"result"];
//         NSString *authCode = nil;
//         if (result.length>0) {
//            NSArray *resultArr = [result componentsSeparatedByString:@"&"];
//            for (NSString *subResult in resultArr) {
//               if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
//                  authCode = [subResult substringFromIndex:10];
//                  break;
//               }
//            }
//         }
//         NSLog(@"授权结果 authCode = %@", authCode?:@"");
//      }];
//   }
//   return YES;
//}
#pragma mark - private
//登陆状态改变
-(void)loginStateChange:(NSNotification *)notification {
    
    
    if (USERID) {//登陆成功加载主窗口控制器
        
        AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
        delegate.isChangeRole=@"yes";
        
        if (_mainController == nil) {
            _mainController = [[MainViewController alloc] init];
        }
        
        self.window.rootViewController = _mainController;
        
        
    }else{//登陆失败加载登陆页面控制器
        
        NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
        [UD setObject:@"0" forKey:@"isLogin"];
        [UD synchronize];
        
        _mainController = nil;
        LoginViewController *loginController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        loginController.isRootViewController = YES;
        [loginController.navBar setHidden:YES];
        SYNavigationController *nav = [[SYNavigationController alloc] initWithRootViewController:loginController];
        
        self.window.rootViewController = nav;
    }
    
    /*
    NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
    if (![[UD objectForKey:@"firstTime"] isEqualToString:@"1"]) {
        [UD setObject:@"1" forKey:@"firstTime"];
        [UD synchronize];
        UIWindow * window = [[UIApplication sharedApplication].delegate window];
        
        NSArray *imgArr = @[@"ios-1",@"ios-2"];
        SplashScreenView *splashView = [[SplashScreenView alloc] initWithFrame:[[UIScreen mainScreen] bounds] imageDataArr:imgArr];
        [window addSubview:splashView];
        
    }
     */
    
}


- (void)checkupVersion {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"3" forKey:@"type"];
    
    [Utils Java_get:@"api/getVersion" parameters:param success:^(NSInteger recode, id jsonObject) {
        
        @try{
            
        NSDictionary *dic = [jsonObject objectForKey:@"re_data"];
        //NSString *newVersion = [dic objectForKey:@"version"]; //新版本
        
        //NSString *localVersion = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleVersion"];
        
        if ([dic isKindOfClass:[NSNull class]] || ![dic isKindOfClass:[NSDictionary class]]) {

            return;

        }
        
        if (dic.allValues.count > 0) {
            
            NSInteger newVersion = [[dic objectForKey:@"version"] integerValue]; //新版本
            
            NSInteger localVersion = [[[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"] integerValue];
            
            int versiontype = [[dic objectForKey:@"versiontype"] intValue];
            int type = [[dic objectForKey:@"type"] intValue];
            
            if (type == 3 && versiontype == 3) {
                
                if (newVersion > localVersion) {
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新版本已发布,请更新后使用" delegate:self cancelButtonTitle:nil otherButtonTitles:@"马上更新", nil];
                    
                    alert.tag = 1001;
                    
                    [alert show];
                    
                }
                
            }
            
        }
        }@catch(NSException * e)
        {
            NSString * error = [NSString stringWithFormat:@"%@",e];
            [Utils alertViewWithMessage:error];
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark -UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 1001){  //更新提示
        
        if (buttonIndex != [alertView cancelButtonIndex]) {
            
            NSString *url = @"https://itunes.apple.com/cn/app/shi-yun/id1341611302?mt=8";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
    }else if (alertView.tag == 10001){
       
       if (buttonIndex != [alertView cancelButtonIndex]) {
          
         [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMessageList" object:nil];
        }
    }
}

-(NSString*)getCurrentTimes{
   
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   
   // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
   
   [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
   
   //现在时间,你可以输出来看下是什么格式
   
   NSDate *datenow = [NSDate date];
   
   //----------将nsdate按formatter格式转成nsstring
   
   NSString *currentTimeString = [formatter stringFromDate:datenow];
   
   NSLog(@"currentTimeString =  %@",currentTimeString);
   
   return currentTimeString;
   
}

#pragma mark 获取当前的控制器
- (UIViewController *)getCurrentVC
{
   UIViewController *result = nil;
   
   UIWindow * window = [[UIApplication sharedApplication] keyWindow];
   if (window.windowLevel != UIWindowLevelNormal)
   {
      NSArray *windows = [[UIApplication sharedApplication] windows];
      for(UIWindow * tmpWin in windows)
      {
         if (tmpWin.windowLevel == UIWindowLevelNormal)
         {
            window = tmpWin;
            break;
         }
      }
   }
   
   UIView *frontView = [[window subviews] objectAtIndex:0];
   id nextResponder = [frontView nextResponder];
   
   if ([nextResponder isKindOfClass:[UIViewController class]])
      result = nextResponder;
   else
      result = window.rootViewController;
   
   return result;
}

@end
